const codeMap = {
  200: 'request:ok',
  400: 'Bad Request',
  401: 'token过期或无效',
  403: '403 Forbidden',
  404: '404 Not Found',
  500: '服务器错误',
  503: '服务不可用',
  unknown: '未知错误'
}

/*
 * @description: 统一返回格式
 * @param {Object} params
 * @return {Object} res
 */
function resHandler(params) {
  const res = Object.assign(
    {
      code: 200
    },
    params
  )

  if (!res.msg) {
    res.msg = codeMap[res.code]
  }
  res.success = String(res.code).startsWith('2') || String(res.code).startsWith('0')
  res.querytime = Date.now()

  return res
}

module.exports = (options, app) => {
  return async function result(ctx, next) {
    try {
      ctx.result = (params) => {
        ctx.body = resHandler(params)
      }
      await next()
    } catch (error) {
      // app.logger.error(error)
      let { status: code = 400, name, message, msg } = error

      switch (error.name) {
        case 'JsonWebTokenError':
        case 'TokenExpiredError':
        case 'UnauthorizedError':
          code = 401
          break
        default:
          break
      }

      app.logger.error('error ==>> ', JSON.stringify(error), '| code ==>>', code, '| name ==>>', name, '| message ==>>', message, '| msg ==>>', msg)

      ctx.body = resHandler({
        code,
        msg,
        errMsg: {
          name,
          message
        }
      })
    }
  }
}
